package com.wanpinghui.wphlibrary.photovideo.view;

import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.githang.statusbar.StatusBarCompat;
import com.wanpinghui.wphlibrary.R;
import com.wanpinghui.wphlibrary.common.dialog.LoadingDialog;
import com.wanpinghui.wphlibrary.photovideo.bean.UploadFileBean;
import com.yunshl.yunshllibrary.utils.LogUtils;
import com.yunshl.yunshllibrary.utils.TextUtil;
import com.yunshl.yunshllibrary.utils.TimeUtil;

import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.utils.BitmapUtil;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/***
 * 功能描述:图片批量裁剪页面
 * 作者:qiujialiu
 * 时间:2016/12/20
 * 版本:1.0
 ***/

public class ClipActivity extends AppCompatActivity {


    //    private ClipView mView;
//    private ClipView mView2;
    private ArrayList<String> paths;
    private ArrayList<UploadFileBean> afterPaths = new ArrayList<>();
    private LinearLayout mLayoutContent;
    private TextView mTextViewTitle;
    // @ViewInject(R.id.clip_view)
    private List<ClipView> mClipViews;
    private int currentIndex = 1;
    private int size = 0;
    private int count;
    private int failCount = 0;
    private float scale;
    private TextView mTextViewClip;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            clipImage();
        }
    };
    private ImageView mViewBacktrack;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarCompat.setStatusBarColor(this, Color.WHITE, true);
            setContentView(R.layout.layout_activity_clip_photo);
        initViews();
        bindEvents();
        initData();
    }



    @Override
    protected void onResume() {
        if(getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        }else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
    }

    private void initViews() {
        mTextViewTitle = (TextView) findViewById(R.id.tv_title);
        mTextViewClip = (TextView) findViewById(R.id.tv_clip);
        mViewBacktrack = (ImageView) findViewById(R.id.mViewBacktrack);
        mLayoutContent = (LinearLayout) findViewById(R.id.ll_content);
        mClipViews = new ArrayList<>();
        LayoutTransition transition = new LayoutTransition();
        transition.getDuration(800);
        ObjectAnimator an = new ObjectAnimator();
        an.setDuration(800).setFloatValues(DensityUtil.getScreenWidth(), 0);
        an.setPropertyName("translationX");
        ObjectAnimator an2 = new ObjectAnimator();
        an2.setDuration(800).setFloatValues(0, -DensityUtil.getScreenWidth());
        an2.setPropertyName("translationX");
        transition.setAnimator(LayoutTransition.APPEARING, an);
        transition.setAnimator(LayoutTransition.CHANGE_APPEARING, transition.getAnimator(LayoutTransition.CHANGE_APPEARING));
        transition.setAnimator(LayoutTransition.DISAPPEARING, transition.getAnimator(LayoutTransition.DISAPPEARING));
        transition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, transition.getAnimator(LayoutTransition.CHANGE_DISAPPEARING));
        mLayoutContent.setLayoutTransition(transition);
    }

    private void bindEvents() {
        addClipListener();
        mViewBacktrack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                BaseDialogManager.getInstance().getBuilder(ClipActivity.this)
//                        .setTitle("提示")
//                        .haveTitle(true)
//                        .setMessage("放弃裁剪不保存此次选择\n是否放弃裁剪")
//                        .setLeftButtonText("是")
//                        .setRightButtonText("继续裁剪")
//                        .setOnClickListener(new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                                if (which==BaseDialogManager.LEFT_BUTTON){
//                                    finish();
//                                }
//                            }
//                        }).create().show();
                finish();
            }
        });
    }

    private void addClipListener() {
        mTextViewClip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (paths != null && paths.size() > 0) {
                    handler.sendEmptyMessageDelayed(1, 500);
                    if (paths.size() == 1) {
                        LoadingDialog.Build(ClipActivity.this).setContent("正在裁剪").show();
                        mTextViewClip.setEnabled(false);
                    }
                }
            }
        });
    }

    private void clipImage() {
        if (paths != null && paths.size() > 0) {
            clipPhoto(paths.get(0), currentIndex - 1);
            paths.remove(0);
            if (paths.size() <= 1){
                mTextViewTitle.setText("裁剪图片");
            }else{
            if (currentIndex < count) {
                mTextViewTitle.setText((currentIndex + 1) + "/" + count);
            }
            }
            if (paths.size() > 0) {
                if (!mClipViews.get(currentIndex).setBmpPath(paths.get(0))) {
                    failCount++;
                    currentIndex++;
                    handler.sendEmptyMessageDelayed(1, 200);
                    return;
                }
                if (mClipViews.get(currentIndex - 1).getParent() != null) {
                    mLayoutContent.removeView(mClipViews.get(currentIndex - 1));
                }
                mLayoutContent.addView(mClipViews.get(currentIndex));
                if (currentIndex > 1) {
                    mLayoutContent.removeView(mClipViews.get(currentIndex - 2));
                }
                currentIndex++;
            } else {
                currentIndex = 1;
            }
        }
    }

    private void clipPhoto(final String path, final int index) {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                if (TextUtil.isEmpty(path)) {
                    subscriber.onNext(path);
                } else {
                    Bitmap bitmap = mClipViews.get(index).getCroppedImage();
                    String path = BitmapUtil.saveBitmapToFile(ClipActivity.this, bitmap, "yunshlImage_" + TimeUtil.formatToFileName(System.currentTimeMillis()) + ".jpg", 100, true);
                    LogUtils.w("clipPhoto pathName " + path);
                    subscriber.onNext(path);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        LogUtils.w("裁剪成功==========size:" + size + ",afterPathSize" + afterPaths.size());
                        mClipViews.get(index).release();
                        afterPaths.add(new UploadFileBean(1, s, true));
                        if (size == afterPaths.size()) {
                            if (failCount > 0) {
                              //  ToastUtil.showToast("剪裁完成，失败" + failCount + "张");
                            } else {
                           //     ToastUtil.showToast("剪裁完成");
                            }
                            failCount = 0;
                            clipFinish();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mClipViews.get(index).release();
                        failCount++;
                        LogUtils.w("裁剪失败==========size:" + size + ",afterPathSize" + afterPaths.size());
                        throwable.printStackTrace();
                        afterPaths.add(new UploadFileBean(1, path, false));
                        if (size == afterPaths.size()) {
                            clipFinish();
                        }
                    }
                });

    }

    private void clipFinish() {
        mTextViewClip.setEnabled(true);
        LoadingDialog.dismissDialog();
        Intent intent = new Intent();
        intent.putExtra("result", afterPaths);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void initData() {
        if (getIntent() != null) {
            paths = getIntent().getStringArrayListExtra("data");
            scale = getIntent().getIntExtra("scale", 1);
        }
        if (paths != null && paths.size() > 0) {
            size = paths.size();
            for (int i = 0; i < size; i++) {
                if (scale != 1) {
                    mClipViews.add(new ClipView(this, scale));
                } else {
                    mClipViews.add(new ClipView(this));
                }

            }

            if (!mClipViews.get(0).setBmpPath(paths.get(0))) {
               // ToastUtil.showToast("图片无法解析，请重新选择!");
                finish();
                return;
            }
            mLayoutContent.addView(mClipViews.get(0));
            count = paths.size();
            mTextViewTitle.setText("1/" + count);
        } else {
      //      ToastUtil.showToast("裁剪出错，没有图片");
            finish();
        }
    }
}
